<?php

$token_api_return = getToken();
$token_api_json = json_decode($token_api_return);
$token = $token_api_json->{'access_token'};

print "get token:$token\n";

#$message_api_return = sendMessage($token);
#$json = json_decode($message_api_return);
#var_dump($json);
/*
if($json->{'code'} == '110'){
	$token_new = refresh_token($token);
	var_dump(sendMessage($token_new));
}
*/
function getToken(){
	$api_address = 'https://oauth.api.189.cn/emp/oauth2/v2/access_token';
	
	//调用接口传递的参数：screen_name为昵称'金山食堂'的url编码,access_token为api授权的登录认证key.
	$send_args = array('grant_type' => 'client_credentials',
				'app_id' => '286020600000031073',
				'app_secret' => 'd8afc663059319efd3fe394e19528862',);
	
	//list message to
	$message_list = array('15110249334');
	
	/*
	//api调用时的since_id参数设置.
	$since_id = getSinceId();
	$send_args['since_id'] = $since_id;
	*/
	
	//$api_method = 'GET';
	$r = new HttpRequest($api_address, HttpRequest::METH_POST);
	#$r->addQueryData($send_args);
	$r->addPostFields($send_args);
	
	try{
		$r->send();
		if ($r->getResponseCode() == 200) {
			$api_return = $r->getResponseBody();		
		}else{
			$api_return = $r->getResponseBody();
		}
	}catch (HttpException $ex) {
		echo $ex;
		die;
	}
	print	$api_return;
	return $api_return;
}

function sendMessage($token){
	$api_address = 'http://api.189.cn/ecp/sms/sendsms';
	
	//调用接口传递的参数：screen_name为昵称'金山食堂'的url编码,access_token为api授权的登录认证key.
	$send_args = array('format' => 'json',
				'app_id' => '286020600000031073',
				'dest' => '15110249334',
				'message' => 'hello world',
	#			'timestamp' => '20120220132723',
	#			'access_token' => 'ebf395b97ace266e11a32447935170751367985642383',
				'dest' => '15110249334',
				);
	
	#286020600000031073ebf395b97ace266e11a3244793517075136798564238320120220132723d8afc663059319efd3fe394e19528862
	$send_args['timestamp'] = time();
	$send_args['access_token'] = $token;
	$send_args['sign'] = md5($send_args['app_id'] . $token . $send_args['timestamp'] . 'd8afc663059319efd3fe394e19528862');
	
	//$api_method = 'GET';
	$r = new HttpRequest($api_address, HttpRequest::METH_GET);
	#$r->addQueryData($send_args);
	$r->addQueryData($send_args);
	
	try{
		$r->send();
		if ($r->getResponseCode() == 200) {
			$api_return = $r->getResponseBody();		
		}else{
			$api_return = $r->getResponseBody();
		}
	}catch (HttpException $ex) {
		echo $ex;
		die;
	}
	
	print $r->getQueryData();
	return $api_return;
}


function refresh_token($token){
		$address = 'https://oauth.api.189.cn/emp/oauth2/v2/access_token';
		$send_args = array('grant_type' => 'refresh_token',
				'refresh_token' => $token,
				'app_id' => '286020600000031073',
				'app_secret' => 'd8afc663059319efd3fe394e19528862',);
	$r = new HttpRequest($address, HttpRequest::METH_POST);
	#$r->addQueryData($send_args);
	$r->addPostFields($send_args);
	
	try{
		$r->send();
		if ($r->getResponseCode() == 200) {
			$api_return = $r->getResponseBody();		
		}else{
			$api_return = $r->getResponseBody();
		}
	}catch (HttpException $ex) {
		echo $ex;
		die;
	}
	print "refresh token response: $api_return";
}

/*
//微博列表
$wb_hash = json_decode($api_return);
$weibo_array = $wb_hash['status'];

//获取要转发的关键字
$keywords = getKeyWorkArray();

foreach($weibo_array as $weibo){
	//文本是否匹配转发条件
	$text = $weibo['text'];
	$keyword_match_tag = 0;
	foreach($keywords as $keyword){
		if(preg_match("/$keyword/", $text)){
			$keyword_match_tag = 1;
			break;
		}
	}

	//时间是否符合条件:考虑到会删微博、修改微博的情况，微博发布时间在10分钟内的暂不转发.
	$create_at = $weibo['create_at'];
	$interval = dateInterval($create_at);
	$interval_match_tag = ($interval >= 60 * 10) ? 1 : 0;

	//是否已转发过
	$wb_id = $weibo['id'];
	$hasBeenSent = checkSent($wb_id);

	if($keyword_match_tag == 1 && $interval_match_tag == 1 && $hasBeenSent == 0){
		//先插入发送记录,以免发送过程中其他的进程检查到没有发送记录
		$receive_num_string = join(',',$message_list);
		$sql = "insert into message_send (`wb_id`, `receive_num`, `status`) VALUES ('$wb_id','$receive_num_string','1')";
		mysql_query($sql) or die "sql '$sql' execute failed: " . mysql_error();

		//发送短信
		
	}
}

function checkSent($id){
	$sql = "select id from message_send where wb_id = '$id' and status = 1";
	$result = mysql_query($sql);
	$count = mysql_num_rows($result) or die "sql '$sql' query failed:" . mysql_error();
	return $count == 0 ? 0 : 1;
}

function dateInterval($create_time){
	if(! defined($create_time)){
		//未获取到发博时间则认为是刚发送,进而阻止短消息的发送
		return 0;
	}
	$interval_seconds = time() - strtotime($create_time);
	return $interval_seconds;
}

function getKeyWorkArray(){
	$keywords = array();
	$directory = dirname(__FILE__);
	$keyword_file = $directory . '/' . 'keyword.conf';
	$fh = fopen($keyword_file,'r') or die "couldn't open file $keyword_file";
	while(!feof($fh)){
		$line = fgets($fh);
		if(preg_match('/^\s+$/', $line) || preg_match('/^\s*\#/', $line)){
			continue;
		}
		print $line; //delete this line
		array_push($keywords, $line);
	}
	fclose($fh);
	return $keywords;
}

function getSinceId(){
	$sql = "select max(id) as max_id from max_id where status = 1;";
	$result = mysql_query($sql);
	$row = mysql_fetch_array($request);
	$since_id = $row['max_id'];
	return $since_id;
}
*/

?>


